package gio

import (
	"gitee.com/maomaomaoge/go-utils/math"
	"os"
	"time"
)

// func:
// ami: 获取 io 写入速度

func DiskIoSpeed() (float64/*readSpeed*/,float64/*writeSpeed*/, error) {
	var (
		resRead float64
		resWrite float64
	)
	count := float64(0)
	mb := make([]byte, 0)
	for i := 0; i < 1024 * 1024 * 10;i++ {
		mb = append(mb, 255)
	}

	n := time.Now()
	f, err := os.OpenFile("tmp.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	if err != nil {
		return 0,0,  err
	}
	for i := 0; i < 20;i++ {
		f.Write(mb)
		f.Sync()
		count += 10
	}
	f.Close()
	over := time.Since(n).Seconds()
	resWrite = math.Round(count/over, 2)

	readTm := time.Now()
	readFile, err := os.OpenFile("tmp.txt", os.O_RDWR, 0660)
	if err != nil {
		return 0,0, err
	}
	cur := int64(0)
	for {
		dataRead := make([]byte, 1024 * 1024)
		at, err := readFile.ReadAt(dataRead, cur)
		if err != nil {
			break
		}
		cur += int64(at)
	}
	readFile.Close()
	rover := time.Since(readTm).Seconds()
	resRead = math.Round(float64(200)/rover, 2)

	os.Remove("tmp.txt")
	return resRead,resWrite, nil
}